<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="form-inline">
        <el-form-item label="学号">
          <el-input 
            v-model="queryParams.sno" 
            placeholder="请输入学号" 
            clearable 
          />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input 
            v-model="queryParams.name" 
            placeholder="请输入姓名" 
            clearable 
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable>
            <el-option label="男" :value="0" />
            <el-option label="女" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="VIP等级">
          <el-select v-model="queryParams.vipLevel" placeholder="请选择VIP等级" clearable>
            <el-option label="普通会员" :value="1" />
            <el-option label="银牌会员" :value="2" />
            <el-option label="金牌会员" :value="3" />
            <el-option label="钻石会员" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleAdd">新增学生</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-table
      v-loading="loading"
      :data="studentUserList"
      border
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="sno" label="学号" width="120" />
      <el-table-column label="头像" width="80" align="center">
        <template #default="scope">
          <el-avatar 
            v-if="scope.row.avatar" 
            :src="getImageUrl(scope.row.avatar)" 
            :size="40"
          />
          <el-avatar v-else :size="40" icon="UserFilled" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column label="性别" width="80" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.sex === 0 ? 'primary' : 'danger'">
            {{ getSexText(scope.row.sex) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="birthday" label="生日" width="120" />
      <el-table-column label="VIP等级" width="120" align="center">
        <template #default="scope">
          <el-tag :type="getVipLevelTagType(scope.row.vipLevel)">
            {{ getVipLevelText(scope.row.vipLevel) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址" min-width="150" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column label="操作" width="320" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleView(scope.row)">详情</el-button>
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            v-if="scope.row.status === 0" 
            type="success" 
            size="small" 
            @click="handleUpdateStatus(scope.row, 1)"
          >
            启用
          </el-button>
          <el-button 
            v-else 
            type="warning" 
            size="small" 
            @click="handleUpdateStatus(scope.row, 0)"
          >
            停用
          </el-button>
          <el-dropdown @command="(command) => handleVipLevelChange(scope.row, command)">
            <el-button type="primary" size="small">
              VIP操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :command="1">设为普通会员</el-dropdown-item>
                <el-dropdown-item :command="2">设为银牌会员</el-dropdown-item>
                <el-dropdown-item :command="3">设为金牌会员</el-dropdown-item>
                <el-dropdown-item :command="4">设为钻石会员</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 学生用户表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="学号" prop="sno" v-if="!form.id">
          <el-input v-model="form.sno" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio :value="0">男</el-radio>
            <el-radio :value="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            placeholder="选择生日"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :limit="1"
            list-type="picture"
            :file-list="fileList"
          >
            <el-button type="primary">选择头像</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过2MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input 
            v-model="form.address" 
            type="textarea"
            :rows="3"
            placeholder="请输入地址" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 学生用户详情对话框 -->
    <el-dialog
      title="学生用户详情"
      v-model="detailVisible"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户ID">{{ detailForm.id }}</el-descriptions-item>
        <el-descriptions-item label="学号">{{ detailForm.sno }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ detailForm.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">
          <el-tag :type="detailForm.sex === 0 ? 'primary' : 'danger'">
            {{ getSexText(detailForm.sex) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="生日">{{ detailForm.birthday }}</el-descriptions-item>
        <el-descriptions-item label="VIP等级">
          <el-tag :type="getVipLevelTagType(detailForm.vipLevel)">
            {{ getVipLevelText(detailForm.vipLevel) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detailForm.status === 1 ? 'success' : 'danger'">
            {{ getStatusText(detailForm.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailForm.createTime }}</el-descriptions-item>
        <el-descriptions-item label="头像" :span="2">
          <el-avatar 
            v-if="detailForm.avatar" 
            :src="getImageUrl(detailForm.avatar)" 
            :size="80"
          />
          <el-avatar v-else :size="80" icon="UserFilled" />
        </el-descriptions-item>
        <el-descriptions-item label="地址" :span="2">{{ detailForm.address || '暂无' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { 
  getStudentUserPage, 
  getStudentUserDetail, 
  createStudentUser, 
  updateStudentUser,
  deleteStudentUser,
  updateStudentUserStatus,
  updateStudentUserVipLevel
} from '@/api/studentUser'
import { handlePageResponse } from '@/utils/pagination'

// 学生用户列表
const studentUserList = ref([])
// 总数据量
const total = ref(0)
// 加载状态
const loading = ref(false)
// 提交加载状态
const submitLoading = ref(false)
// 表单对话框可见状态
const dialogVisible = ref(false)
// 详情对话框可见状态
const detailVisible = ref(false)
// 表单对话框标题
const dialogTitle = ref('新增学生')
// 表单引用
const formRef = ref(null)
// 图片上传文件列表
const fileList = ref([])

// 上传URL
const uploadUrl = '/api/file/uploadImage/avatar'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sno: '',
  name: '',
  sex: null,
  vipLevel: null,
  status: null
})

// 表单数据
const form = reactive({
  id: null,
  sno: '',
  name: '',
  sex: 0,
  birthday: '',
  avatar: '',
  address: ''
})

// 详情表单
const detailForm = ref({})

// 表单验证规则
const rules = {
  sno: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
}

// 获取图片URL
const getImageUrl = (imagePath) => {
  if (!imagePath) return ''
  return `/api/file/download?fileName=${imagePath}`
}

// 获取性别文本
const getSexText = (sex) => {
  return sex === 0 ? '男' : '女'
}

// 获取VIP等级文本
const getVipLevelText = (level) => {
  const levelMap = {
    1: '普通会员',
    2: '银牌会员',
    3: '金牌会员',
    4: '钻石会员'
  }
  return levelMap[level] || '未知等级'
}

// 获取VIP等级标签类型
const getVipLevelTagType = (level) => {
  const typeMap = {
    1: 'info',
    2: 'warning',
    3: 'success',
    4: 'danger'
  }
  return typeMap[level] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  return status === 1 ? '启用' : '停用'
}

// 初始化数据
onMounted(async () => {
  await fetchData()
})

// 获取学生用户列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getStudentUserPage(queryParams)
    const { list, total: totalCount } = handlePageResponse(res)
    studentUserList.value = list
    total.value = totalCount
  } catch (error) {
    console.error('获取学生用户列表失败:', error)
    ElMessage.error('获取学生用户列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchData()
}

// 重置查询
const resetQuery = () => {
  queryParams.sno = ''
  queryParams.name = ''
  queryParams.sex = null
  queryParams.vipLevel = null
  queryParams.status = null
  handleQuery()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.pageNum = 1
  fetchData()
}

// 处理添加学生用户
const handleAdd = () => {
  dialogTitle.value = '新增学生'
  resetForm()
  fileList.value = []
  dialogVisible.value = true
}

// 处理编辑学生用户
const handleEdit = (row) => {
  dialogTitle.value = '编辑学生'
  resetForm()
  Object.assign(form, row)
  
  // 设置头像文件列表
  fileList.value = row.avatar ? [{
    name: row.avatar.split('/').pop(),
    url: getImageUrl(row.avatar)
  }] : []
  
  dialogVisible.value = true
}

// 处理查看学生用户详情
const handleView = async (row) => {
  try {
    const res = await getStudentUserDetail(row.id)
    if (res.code === 200) {
      detailForm.value = res.data
      detailVisible.value = true
    }
  } catch (error) {
    console.error('获取学生用户详情失败:', error)
    ElMessage.error('获取学生用户详情失败')
  }
}

// 处理删除学生用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认要删除学生用户"${row.name}"吗？此操作将永久删除该用户，无法恢复！`,
    '警告',
    {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteStudentUser(row.id)
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      fetchData()
    } catch (error) {
      console.error('删除学生用户失败:', error)
      ElMessage({
        type: 'error',
        message: '删除失败，请稍后再试'
      })
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

// 处理更新学生用户状态
const handleUpdateStatus = (row, status) => {
  const statusText = getStatusText(status)
  ElMessageBox.confirm(
    `确认将学生用户"${row.name}"设为${statusText}状态吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(async () => {
    try {
      await updateStudentUserStatus(row.id, status)
      ElMessage({
        type: 'success',
        message: `状态更新成功!`
      })
      fetchData()
    } catch (error) {
      console.error('更新学生用户状态失败:', error)
      ElMessage({
        type: 'error',
        message: '状态更新失败'
      })
    }
  })
}

// 处理VIP等级变更
const handleVipLevelChange = (row, vipLevel) => {
  const levelText = getVipLevelText(vipLevel)
  ElMessageBox.confirm(
    `确认将学生用户"${row.name}"的VIP等级设为${levelText}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(async () => {
    try {
      await updateStudentUserVipLevel(row.id, vipLevel)
      ElMessage({
        type: 'success',
        message: `VIP等级更新成功!`
      })
      fetchData()
    } catch (error) {
      console.error('更新VIP等级失败:', error)
      ElMessage({
        type: 'error',
        message: 'VIP等级更新失败'
      })
    }
  })
}

// 上传前验证
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJpgOrPng) {
    ElMessage.error('只能上传JPG/PNG格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (response, file) => {
  if (response.code === 200) {
    form.avatar = response.data
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 上传失败回调
const handleUploadError = () => {
  ElMessage.error('头像上传失败')
}

// 重置表单
const resetForm = () => {
  form.id = null
  form.sno = ''
  form.name = ''
  form.sex = 0
  form.birthday = ''
  form.avatar = ''
  form.address = ''
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async valid => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      if (form.id) {
        await updateStudentUser(form)
        ElMessage({
          type: 'success',
          message: '更新成功!'
        })
      } else {
        await createStudentUser(form)
        ElMessage({
          type: 'success',
          message: '创建成功!'
        })
      }
      dialogVisible.value = false
      fetchData()
    } catch (error) {
      console.error('保存学生用户失败:', error)
      ElMessage({
        type: 'error',
        message: '保存失败，请稍后再试'
      })
    } finally {
      submitLoading.value = false
    }
  })
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

.upload-demo {
  width: 100%;
}

.el-upload {
  width: 100%;
}
</style>
